<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload Test</title>
</head>
<body>
    <h1>File Upload Test</h1>
    <form id="uploadForm" enctype="multipart/form-data">
        <label for="image">Select an image:</label>
        <input type="file" id="image" name="image"><br><br>
        <label for="type">Type:</label>
        <input type="text" id="type" name="type"><br><br>
        <input type="button" value="Upload and Submit" onclick="uploadFile()">
    </form>

    <script>
        async function uploadFile() {
            const form = document.getElementById('uploadForm');
            const formData = new FormData();

            const fileInput = document.getElementById('image');
            const typeInput = document.getElementById('type');

            if (fileInput.files.length === 0) {
                alert("Please select a file.");
                return;
            }

            // Append file to formData
            formData.append('image', fileInput.files[0]);

            try {
                // First, upload the file to get a temporary file name
                const uploadResponse = await fetch('http://localhost:3000/api/user/drug_knowledge', {
                    method: 'POST',
                    body: formData
                });

                if (!uploadResponse.ok) {
                    throw new Error('File upload failed');
                }

                const uploadResult = await uploadResponse.json();

                // Now submit the form with the temporary file name
                const submissionData = {
                    type: typeInput.value,
                    tempFileName: uploadResult.tempFileName
                };

                const submissionResponse = await fetch('http://localhost:3000/api/submit-data', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer your_jwt_token_here'
                    },
                    body: JSON.stringify(submissionData)
                });

                if (!submissionResponse.ok) {
                    throw new Error('Data submission failed');
                }

                const submissionResult = await submissionResponse.json();
                alert('Upload and submission successful!');
                console.log('Submission result:', submissionResult);

            } catch (error) {
                console.error('Error:', error);
                alert('An error occurred: ' + error.message);
            }
        }
    </script>
</body>
</html>
